package com.starsky.websocket.handler;

import com.alibaba.fastjson.JSONObject;
import com.starsky.websocket.domain.Result;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 不需要获取请求url 参数方式 处理器
 */
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Logger log = LoggerFactory.getLogger(WebSocketHandler.class);
    public static Map<String, ChannelHandlerContext> queue = new ConcurrentHashMap<>();

    /**
     * 打开连接
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        queue.put(ctx.channel().id().toString(), ctx);
        log.info("与客户端建立连接，通道开启...");
    }

    /**
     * 关闭连接
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        queue.remove(ctx.channel().id().toString());
        log.info("与客户端断开连接，通道关闭...");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        log.info("客户端收到服务器数据:" + msg.text());
        ctx.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(new Result<String>(200, "连接成功", "Hello WebSocket..."))));
    }

    /**
     * 异常捕获
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception {
        Channel channel = ctx.channel();
        log.error("连接异常：[" + channel.remoteAddress() + "] ");
        ctx.close().sync();
    }
}
